const winston = require('winston');
const morgan = require('morgan');
const path = require('path');

// 定义日志格式
const logFormat = winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
    winston.format.printf(({ timestamp, level, message, ...meta }) => {
        // 美化输出的 JSON
        const metaString = Object.keys(meta).length ? 
            '\n' + JSON.stringify(meta, null, 2) : '';
        
        return `[${timestamp}] ${level.toUpperCase()}: ${message}${metaString}`;
    })
);

// 创建 Winston logger
const logger = winston.createLogger({
    format: logFormat,
    transports: [
        // 错误日志文件
        new winston.transports.File({
            filename: path.join(__dirname, '../../logs/error.log'),
            level: 'error',
            maxsize: 10 * 1024 * 1024, // 10MB
            maxFiles: 5,
            tailable: true
        }),
        // 所有日志文件
        new winston.transports.File({
            filename: path.join(__dirname, '../../logs/combined.log'),
            maxsize: 10 * 1024 * 1024, // 10MB
            maxFiles: 5,
            tailable: true
        })
    ]
});

// 在开发环境下，同时输出到控制台
if (process.env.NODE_ENV !== 'production') {
    logger.add(new winston.transports.Console({
        format: winston.format.combine(
            winston.format.colorize(),
            logFormat
        )
    }));
}

// 创建自定义的 Morgan 格式
const morganFormat = ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :response-time ms';

// 创建 Morgan stream，将日志写入 Winston
const morganStream = {
    write: (message) => {
        logger.info('HTTP Access Log', { httpLog: message.trim() });
    }
};

// 导出 Morgan 中间件
const httpLogger = morgan(morganFormat, { stream: morganStream });

module.exports = {
    logger,
    httpLogger
};